<template>
  <el-select
    v-model="selectedLabels"
    multiple
    collapse-tags
    filterable
    placeholder="请选择节点"
    style="width: 400px"
    :options="[]"
    clearable
    @update:modelValue="onSelectLabelsChange"
  >
    <el-option
      :label="''"
      :value="''"
      disabled
      style="height: 400px; overflow: auto"
    >
      <div style="height: 400px; overflow: auto">
        <el-tree-v2
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          show-checkbox
          :height="400"
          :check-strictly="false"
          @check="handleCheckChange"
        />
      </div>
    </el-option>
  </el-select>

  <div style="margin-top: 16px">
    <strong>选中 ID 列表：</strong> {{ selectedIds.join(", ") }}
  </div>
</template>

<script setup>



import { ref, watch } from "vue";
const treeRef = ref(null);
const selectedLabels = ref([]);
const selectedIds = ref([]);

function generateLargeTreeDataMultiLevel(parentCount, childrenPerParent) {
  const data = [];
  let idCounter = 1;

  for (let p = 1; p <= parentCount; p++) {
    const children = [];
    for (let c = 1; c <= childrenPerParent; c++) {
      children.push({
        id: idCounter++,
        label: `节点 ${idCounter - 1}`,
      });
    }
    data.push({
      id: idCounter++,
      label: `父节点 ${p}`,
      children,
    });
  }

  for (let i = 0; i < 10 && i < data.length; i++) {
    const parent = data[i];
    if (parent.children && parent.children.length) {
      parent.children = parent.children.map((child) => {
        return {
          ...child,
          children: [
            { id: idCounter++, label: `孙节点 ${idCounter - 1}` },
            { id: idCounter++, label: `孙节点 ${idCounter - 1}` },
            { id: idCounter++, label: `孙节点 ${idCounter - 1}` },
          ],
        };
      });
    }
  }

  return data;
}

const treeData = generateLargeTreeDataMultiLevel(1000, 15);
const defaultProps = {
  children: "children",
  label: "label",
};

// 树节点选中触发
function handleCheckChange() {
  const checkedKeys = treeRef.value.getCheckedKeys();
  selectedIds.value = checkedKeys;

  const checkedNodes = treeRef.value.getCheckedNodes();
  selectedLabels.value = checkedNodes.map((node) => node.label);
}

// 监听 select 标签删除，同步更新树选中
function onSelectLabelsChange(newLabels) {
  console.log(newLabels);

  // 根据标签名找对应节点 id，简化逻辑：用树扁平搜索
  const allNodes = [];
  function flatten(nodes) {
    nodes.forEach((node) => {
      allNodes.push(node);
      if (node.children) flatten(node.children);
    });
  }
  flatten(treeData);

  // 找到新标签对应节点id
  const newSelectedIds = allNodes
    .filter((node) => newLabels.includes(node.label))
    .map((node) => node.id);

  selectedIds.value = newSelectedIds;

  // 同步树选中
  treeRef.value.setCheckedKeys(newSelectedIds, true);

  // 更新标签
  selectedLabels.value = newLabels;
}
</script>
